
import { join } from 'node:path'
import { readdirSync,existsSync } from "node:fs"
import { cwd } from "node:process"
import { spawnSync } from 'node:child_process'
import { getCommandFile } from "@mcswift/node"
const main = ()=>{
  console.log("开始执行构建")
  const entries = collectEntry()
  const viteBinPath = getCommandFile("vite")
  console.debug(viteBinPath)
  if(!viteBinPath){
    throw new Error("vite 命令不存在")
  }
  for(const [name,path] of Object.entries(entries)){
    console.log(`开始构建 ${name}`)
    spawnSync(viteBinPath,["build"],{
      env:{
        LIB_NAME:name,
        LIB_ENTRY:path
      },
      cwd:join(cwd()),
      stdio:["inherit","inherit","inherit"],
      shell:true
    })
    console.log(`构建 ${name} 完成`)
  }
  console.log("全部构建完成")
}
const collectEntry = ()=>{
  // 定义返回元组
  const result:[ name:string, path:string][] = []
  const componentsDir = join(cwd(), "src/components")
  const dirents = readdirSync(componentsDir,{
    withFileTypes:true
  })
  if(dirents.length===0){
    console.warn("src/components 目录为空")
  };
  for(const dirent of dirents ){
    // 不是目录就不处理
    if(!dirent.isDirectory())continue
    // 在这里预处理成绝对路径
    const entryFilePath  = join(componentsDir, dirent.name, "index.ts");
    // 检测路径是否存在
    if(!existsSync(entryFilePath))continue;
    result.push([
      dirent.name,
      entryFilePath
    ])
  }
  if(result.length===0){
    console.warn("没找到合适的组件")
  }
  return Object.fromEntries(result)
}
main();
